import {getDataSet} from "../../utils/utils";
import FileUploader from "../../utils/http-uploader"

Component({
    properties: {
        files: {
            type: Array,
            value: []
        },
        maxCount : {
            type : Number,
            value : 1
        },
        sizeType : {
            type : Array,
            value : ['original', 'compressed']
        },
        sourceType : {
            type : Array,
            value :  ['album', 'camera'],
        },
        size : {
            type : Number,
            value : 2
        }
    },
    data: {
        uploadStatusEnum : {
            UPLOADING : 1,
            SUCCESS : 2,
            ERROR : 0
        }
    },
    observers: {
        files: function(value){
            // if(!value.length){
            //     return
            // }

            console.log(value);

            const _files = [];
            value.forEach((item, index) => {
                const file = {
                    id: item.id,
                    key: index + '',
                    path: item.path,
                    status: this.data.uploadStatusEnum.SUCCESS,
                    error: ''
                }
                _files.push(file)
            })
            this.setData({
                _files
            })
        }
    },
    methods: {
        handlePreview : function (event){
            const index = getDataSet(event,'index')
            const urls = this.data._files.map(item=>item.path)
            wx.previewImage({
                urls : urls,
                current : this.data._files[index].path
            })
        },
        handleDelete : function (event){
            const index = getDataSet(event, 'index')
            console.log(index);
            const deleted = this.data._files.splice(index, 1)
            this.setData({
                _files : this.data._files
            })
            this.triggerEvent('delete',{index,item : deleted})
        },
        handleChooseImage :async  function (event){
            const res= await wx.chooseImage({
                count : this.data.maxCount,
                sizeType : this.data.sizeType,
                sourceType : this.data.sourceType
            })
            // console.log(res);


            this.triggerEvent("choose",{files : res.tempFiles})

            const _files = this._filesFilter(res.tempFiles)

            this.setData({_files})

            const uploadTask = _files.filter(item=> item.status === this.data.uploadStatusEnum.UPLOADING)

            // 上传筛选出正在上传的图片
            this._executeUpload(uploadTask);
        },
        _filesFilter : function (tempFile){
            const res = []
            let error = ''
            tempFile.forEach((item,index)=>{
                if(item.size > 1024 * 1024 * this.data.size){
                    error += `图片大小不能超过${this.data.size}M`
                    this.triggerEvent("validatefail",{item,error})
                }

                const length = this.data._files.length

                res.push({
                    path : item.path,
                    key : index + length + '',
                    status : error ?  this.data.uploadStatusEnum.ERROR :  this.data.uploadStatusEnum.UPLOADING,
                    error : ''
                })
            })

            return this.data._files.concat(res)

        },
        // 上传到图片服务器
        async _executeUpload(uploadTask){
            // console.log('上传', uploadTask);
            const success = [];
            for(let file of uploadTask){
                console.log(file);
                try{
                    const res = await FileUploader.upload(file.path, file.key)
                    file.id = res[0].id
                    
                    file.status = this.data.uploadStatusEnum.SUCCESS;
                    console.log(file.key);
                    this.data._files[file.key] = file;

                    // console.log(this.data._files);
                    success.push(file)
                }catch(e){
                    file.status = this.data.uploadStatusEnum.ERROR
                    file.error = e;
                    this.triggerEvent("uploadfail", {file, error: e})
                }

                this.setData({
                    _files: this.data._files
                })
                
                if(success.length > 0){
                    this.triggerEvent("uploadsuccess", {files: success})
                }
            }
        }
    }
});
